from django.contrib.auth.mixins import UserPassesTestMixin


class OwnerMixin(UserPassesTestMixin):
    """拥有者混合类

    用户只能删除或修改自己的文章，如果试图删除或修改别人的文章，会返回403（Forbidden）错误页面
    """
    def test_func(self):
        post = self.get_object()
        if post.user == self.request.user:
            return True
        return False

# 第二种实现方式
# from django.core.exceptions import PermissionDenied
# class OwnerMixin:
#     def dispatch(self, request, *args, **kwargs):
#         if request.user != self.get_object().user:
#             raise PermissionDenied
#         return super().dispatch(self, request, *args, **kwargs)